package com.jokerpan.project.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/websocket/{id}")
public class WebSocketServer {
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private static Logger log = LogManager.getLogger(WebSocketServer.class);
    private String id = "";

    /**
     * 连接建立成功调用的方法
     * @param id 用户的标识
     * @param session 会话
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id, Session session) {
        //设置超时时间
        session.setMaxIdleTimeout(3600000);
        this.session = session;
        //接收到发送消息的人员编号
        this.id = id;
        //加入set中
        if (webSocketMap.containsKey(id)){
            webSocketMap.remove(id);
        }else {
            //在线数加1
            addOnlineCount();
        }
        webSocketMap.put(id, this);
        log.info("用户【"+id+"】加入！当前在线人数为" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从map中删除
        webSocketMap.remove(this.id);
        if (getOnlineCount() > 0){
            //在线数减1
            subOnlineCount();
        }
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 会话
     * */
    @OnMessage
    public void onMessage(String message, Session session){
        log.info("来自客户端的消息:" + message);
        //可以自己约定字符串内容，比如 内容|0 表示信息群发，内容|X 表示信息发给用户名为X的用户
        String sendMessage = message.split("[|]")[0];
        String sendUserId = message.split("[|]")[1];
        try {
            if(sendUserId.equals("0")) {
                sendtoAll(sendMessage);
            }
            else {
                sendMessageTo(sendMessage, sendUserId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public void sendMessageTo(String message,String sendUserId) throws IOException{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = format.format(new Date());
        String msg = "用户【" + id + "】发来消息：" + message + "-" + now;
        if (webSocketMap.get(sendUserId) != null) {
            if(!id.equals(sendUserId)){
                webSocketMap.get(sendUserId).sendMessage(msg);
            } else {
                //自己不能给自己发送消息
                //webSocketMap.get(sendUserId).sendMessage(message);
            }
        } else {
            msg = sendUserId + "_notOnline：" + msg.split("：")[1];
            //当发送用户不在线时发送给自己接收
            webSocketMap.get(id).sendMessage(msg);
        }
    }



    /**
     * 发送信息给所有人
     * @param message
     * @throws IOException
     */
    public void sendtoAll(String message) throws IOException {
        for (String key : webSocketMap.keySet()) {
            try {
                webSocketMap.get(key).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
